package cn.itrip.controller;

import cn.itrip.DTO.ItripHotelOrderDTO;
import cn.itrip.DTO.ItripPersonalHotelOrderDTO;
import cn.itrip.DTO.ItripPersonalOrderRoomDTO;
import cn.itrip.DTO.OrderDTO;
import cn.itrip.entity.ItripHotelOrder;
import cn.itrip.entity.ItripHotelRoom;
import cn.itrip.entity.ItripUser;
import cn.itrip.entity.ItripUserLinkUser;
import cn.itrip.service.*;
import cn.itrip.utils.*;
import cn.itrip.vo.R;
import cn.itrip.vo.biz.ItripAddHotelOrderVO;
import cn.itrip.vo.biz.ItripHotelOrderVO;
import cn.itrip.vo.biz.ItripSearchOrderVO;
import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/hotelorder")
public class HotelorderController {

    @Resource
    private ItripHotelService itripHotelService;
    @Resource
    private ItripHotelRoomService itripHotelRoomService;
    @Resource
    private ItripHotelTempStoreService itripHotelTempStoreService;
    @Resource
    private ItripHotelOrderService itripHotelOrderService;
    @Resource
    private TokenService tokenService;

    @ApiOperation(value = "预生成订单信息")
    @ApiResponses({ @ApiResponse(code = 200, message = "OK",response = ItripHotelOrderDTO.class) })
    @PostMapping("/getpreorderinfo")
    public R getPreorderInfo(@RequestBody ItripHotelOrderVO hotelOrderVO){
        ItripHotelOrderDTO hotelOrderDTO = new ItripHotelOrderDTO();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date CheckInDate = MyDateFormat.MyDateFormat(hotelOrderVO.getCheckInDate());
        hotelOrderDTO.setCheckInDate(format.format(CheckInDate));
        Date CheckOutDate = MyDateFormat.MyDateFormat(hotelOrderVO.getCheckOutDate());
        hotelOrderDTO.setCheckOutDate(format.format(CheckOutDate));
        hotelOrderDTO.setCount(hotelOrderVO.getCount());
        hotelOrderDTO.setHotelId(hotelOrderVO.getHotelId());
        hotelOrderDTO.setRoomId(hotelOrderVO.getRoomId());
        Long HotelId = hotelOrderVO.getHotelId();
        Long RoomId = hotelOrderVO.getRoomId();
        String HotelName = itripHotelService.getHotelByHotelId(HotelId).getHotelName();
        hotelOrderDTO.setHotelName(HotelName);
        Double Price = itripHotelRoomService.getItripHotelRoomByHotelAndId(HotelId, RoomId).getRoomPrice();
        hotelOrderDTO.setPrice(Price);
        Integer store = itripHotelTempStoreService.getStoreByHotelAndRoomId(HotelId, RoomId).getStore();
        hotelOrderDTO.setStore(store);
        return R.success("获取成功",hotelOrderDTO);
    }

    @ApiOperation(value = "添加订单")
    @ApiResponses({ @ApiResponse(code = 200, message = "OK",response = OrderDTO.class) })
    @PostMapping(value = "/addhotelorder",headers = {"token"})
    public R addHotelorder(@RequestBody ItripAddHotelOrderVO itripAddHotelOrderVO, HttpServletRequest request){
        String tokenString = request.getHeader("token");
        ItripUser currentUser = tokenService.load(tokenString);
        List<ItripUserLinkUser> linkUserList = itripAddHotelOrderVO.getLinkUser();
        if (EmptyUtils.isEmpty(currentUser)) {
            R r = new R();
            r.setErrorCode("100000");
            r.setMsg("token失效，请重登录");
            return r;
        }
        try {
            //判断库存是否充足
            Boolean flag = itripHotelTempStoreService.validateRoomStore(itripAddHotelOrderVO);
            if (flag && null != itripAddHotelOrderVO) {
                //计算订单的预定天数
                Integer days = DateUtil.getBetweenDates(
                        itripAddHotelOrderVO.getCheckInDate(), itripAddHotelOrderVO.getCheckOutDate()
                ).size() - 1;
                if (days <= 0) {
                    R r = new R();
                    r.setErrorCode("100505");
                    r.setMsg("退房日期必须大于入住日期");
                    return r;
                }
                ItripHotelOrder itripHotelOrder = new ItripHotelOrder();
                itripHotelOrder.setId(itripAddHotelOrderVO.getId());
                itripHotelOrder.setUserId(currentUser.getId());
                itripHotelOrder.setOrderType(itripAddHotelOrderVO.getOrderType());
                itripHotelOrder.setHotelId(itripAddHotelOrderVO.getHotelId());
                itripHotelOrder.setHotelName(itripAddHotelOrderVO.getHotelName());
                itripHotelOrder.setRoomId(itripAddHotelOrderVO.getRoomId());
                itripHotelOrder.setCount(itripAddHotelOrderVO.getCount());
                itripHotelOrder.setCheckInDate(itripAddHotelOrderVO.getCheckInDate());
                itripHotelOrder.setCheckOutDate(itripAddHotelOrderVO.getCheckOutDate());
                itripHotelOrder.setNoticePhone(itripAddHotelOrderVO.getNoticePhone());
                itripHotelOrder.setNoticeEmail(itripAddHotelOrderVO.getNoticeEmail());
                itripHotelOrder.setSpecialRequirement(itripAddHotelOrderVO.getSpecialRequirement());
                itripHotelOrder.setIsNeedInvoice(itripAddHotelOrderVO.getIsNeedInvoice());
                itripHotelOrder.setInvoiceHead(itripAddHotelOrderVO.getInvoiceHead());
                itripHotelOrder.setInvoiceType(itripAddHotelOrderVO.getInvoiceType());
                itripHotelOrder.setCreatedBy(currentUser.getId());
                StringBuilder linkUserName = new StringBuilder();
                int size = linkUserList.size();
                for (int i = 0; i < size; i++) {
                    if (i != size - 1) {
                        linkUserName.append(linkUserList.get(i).getLinkUserName() + ",");
                    } else {
                        linkUserName.append(linkUserList.get(i).getLinkUserName());
                    }
                }
                itripHotelOrder.setLinkUserName(linkUserName.toString());
                itripHotelOrder.setBookingDays(days);
                if (tokenString.startsWith("token:PC")) {
                    itripHotelOrder.setBookType(0);
                } else if (tokenString.startsWith("token:MOBILE")) {
                    itripHotelOrder.setBookType(1);
                } else {
                    itripHotelOrder.setBookType(2);
                }
                //支付之前生成的订单的初始状态为未支付
                itripHotelOrder.setOrderStatus(0);
                try {
                    //生成订单号：机器码 +日期+（MD5）（商品IDs+毫秒数+1000000的随机数）
                    StringBuilder md5String = new StringBuilder();
                    md5String.append(itripHotelOrder.getHotelId());
                    md5String.append(itripHotelOrder.getRoomId());
                    md5String.append(System.currentTimeMillis());
                    md5String.append(Math.random() * 1000000);
                    String md5 = MD5.getMd5(md5String.toString(), 6);

                    //生成订单编号
                    StringBuilder orderNo = new StringBuilder();
                    orderNo.append("D1000001");
                    orderNo.append(DateUtil.format(new Date(), "yyyyMMddHHmmss"));
                    orderNo.append(md5);
                    itripHotelOrder.setOrderNo(orderNo.toString());
                    //计算订单的总金额
                    itripHotelOrder.setPayAmount(itripHotelOrderService.getOrderPayAmount(days * itripAddHotelOrderVO.getCount(), itripAddHotelOrderVO.getRoomId()));

                    Map<String, String> map = itripHotelOrderService.itriptxAddItripHotelOrder(itripHotelOrder, linkUserList);
                    return R.success("生成订单成功",map);
                } catch (Exception e) {
                    e.printStackTrace();
                    R r = new R();
                    r.setErrorCode("100505");
                    r.setMsg("生成订单失败");
                    return r;
                }
            } else if (flag && null == itripAddHotelOrderVO) {
                R r = new R();
                r.setErrorCode("100506");
                r.setMsg("不能提交空，请填写订单信息");
                return r;
            } else {
                R r = new R();
                r.setErrorCode("100507");
                r.setMsg("库存不足");
                return r;
            }
        } catch (Exception e) {
            e.printStackTrace();
            R r = new R();
            r.setErrorCode("100508");
            r.setMsg("系统异常");
            return r;
        }
    }
    @ApiOperation(value = "获取个人订单信息")
    @ApiResponses({ @ApiResponse(code = 200, message = "OK") })
    @GetMapping("/getpersonalorderinfo/{orderId}")
    public R getPersonalOrderInfo(@PathVariable String orderId,HttpServletRequest request){
        String tokenString = request.getHeader("token");
        ItripUser currentUser = tokenService.load(tokenString);
        if (null != currentUser) {
            if (null == orderId || "".equals(orderId)) {
                R r = new R();
                r.setErrorCode("100525");
                r.setMsg("请传递参数：orderId");
                return r;
            }
            try {
                ItripHotelOrder hotelOrder = itripHotelOrderService.getItripHotelOrderById(Long.valueOf(orderId));
                if (null != hotelOrder) {
                    ItripPersonalHotelOrderDTO itripPersonalHotelOrderDTO = new ItripPersonalHotelOrderDTO();
                    itripPersonalHotelOrderDTO.setId(hotelOrder.getId());
                    itripPersonalHotelOrderDTO.setBookType(hotelOrder.getBookType());
                    itripPersonalHotelOrderDTO.setCreationDate(hotelOrder.getCreationDate());
                    itripPersonalHotelOrderDTO.setOrderNo(hotelOrder.getOrderNo());
                    //查询预订房间的信息
                    ItripHotelRoom room = itripHotelRoomService.getItripHotelRoomById(hotelOrder.getRoomId());
                    if (EmptyUtils.isNotEmpty(room)) {
                        itripPersonalHotelOrderDTO.setRoomPayType(room.getPayType());
                    }
                    Integer orderStatus = hotelOrder.getOrderStatus();
                    itripPersonalHotelOrderDTO.setOrderStatus(orderStatus);
                    //订单状态（0：待支付 1:已取消 2:支付成功 3:已消费 4:已点评）
                    //{"1":"订单提交","2":"订单支付","3":"支付成功","4":"入住","5":"订单点评","6":"订单完成"}
                    //{"1":"订单提交","2":"订单支付","3":"订单取消"}
                    if (orderStatus == 1) {
                        itripPersonalHotelOrderDTO.setOrderProcess("订单取消");
                        itripPersonalHotelOrderDTO.setProcessNode("3");
                    } else if (orderStatus == 0) {
                        itripPersonalHotelOrderDTO.setOrderProcess("订单支付");
                        itripPersonalHotelOrderDTO.setProcessNode("2");//订单支付
                    } else if (orderStatus == 2) {
                        itripPersonalHotelOrderDTO.setOrderProcess("支付成功");
                        itripPersonalHotelOrderDTO.setProcessNode("3");//支付成功（未出行）
                    } else if (orderStatus == 3) {
                        itripPersonalHotelOrderDTO.setOrderProcess("订单点评");
                        itripPersonalHotelOrderDTO.setProcessNode("5");//订单点评
                    } else if (orderStatus == 4) {
                        itripPersonalHotelOrderDTO.setOrderProcess("订单完成");
                        itripPersonalHotelOrderDTO.setProcessNode("6");//订单完成
                    } else {
                        itripPersonalHotelOrderDTO.setOrderProcess(null);
                        itripPersonalHotelOrderDTO.setProcessNode(null);
                    }
                    itripPersonalHotelOrderDTO.setPayAmount(hotelOrder.getPayAmount());
                    itripPersonalHotelOrderDTO.setPayType(hotelOrder.getPayType());
                    itripPersonalHotelOrderDTO.setNoticePhone(hotelOrder.getNoticePhone());
                    return R.success("获取个人订单信息成功",itripPersonalHotelOrderDTO);
                } else {
                    R r = new R();
                    r.setErrorCode("100526");
                    r.setMsg("没有相关订单信息");
                    return r;
                }
            } catch (Exception e) {
                e.printStackTrace();
                R r = new R();
                r.setErrorCode("100527");
                r.setMsg("获取个人订单信息错误");
                return r;
            }
        } else {
            R r = new R();
            r.setErrorCode("100000");
            r.setMsg("token失效，请重登录");
            return r;
        }
    }

    @ApiOperation(value = "查询个人酒店订单列表")
    @ApiResponses({ @ApiResponse(code = 200, message = "OK") })
    @PostMapping("/getpersonalorderlist")
    public R getPersonalOrderList(@RequestBody ItripSearchOrderVO itripSearchOrderVO, HttpServletRequest request){
        Integer orderType = itripSearchOrderVO.getOrderType();
        Integer orderStatus = itripSearchOrderVO.getOrderStatus();
        String tokenString = request.getHeader("token");
        ItripUser currentUser = tokenService.load(tokenString);
        if (orderType<=0){
            itripSearchOrderVO.setOrderType(null);
        }
        if (orderStatus<=0){
            itripSearchOrderVO.setOrderStatus(null);
        }
        R r = new R();
        if (null != currentUser) {
            if (orderType == null) {
                r.setErrorCode("100501");
                r.setMsg("请传递参数：orderType");
                return r;
            }
            if (orderStatus == null) {
                r.setErrorCode("100502");
                r.setMsg("请传递参数：orderStatus");
                return r;
            }
            try {
                Page page = itripHotelOrderService.queryOrderPageByMap(itripSearchOrderVO);
                return R.success("获取个人订单列表成功", page);
            } catch (Exception e) {
                e.printStackTrace();
                r.setErrorCode("100503");
                r.setMsg("获取个人订单列表错误");
                return r;
            }

        } else {
            r.setErrorCode("100000");
            r.setMsg("token失效，请重登录");
            return r;
        }
    }

    @ApiOperation(value = "查询个人订单房型信息")
    @ApiResponses({ @ApiResponse(code = 200, message = "OK") })
    @GetMapping("/getpersonalorderroominfo/{orderId}")
    public R getpersonalorderroominfo(@PathVariable String orderId,HttpServletRequest request){
        String tokenString = request.getHeader("token");
        ItripUser currentUser = tokenService.load(tokenString);
        R r = new R();
        if (null != currentUser) {
            if (null == orderId || "".equals(orderId)) {
                r.setErrorCode("100529");
                r.setMsg("请传递参数：orderId");
                return r;
            }
            try {
                ItripPersonalOrderRoomDTO dto = itripHotelOrderService.getItripHotelOrderRoomInfoById(Long.valueOf(orderId));
                if (null != dto) {
                    return R.success("获取个人订单房型信息成功", dto);
                } else {
                    r.setErrorCode("100530");
                    r.setMsg("没有相关订单房型信息");
                    return r;
                }
            } catch (Exception e) {
                e.printStackTrace();
                r.setErrorCode("100531");
                r.setMsg("获取个人订单房型信息错误");
                return r;
            }
        } else {
            r.setErrorCode("100000");
            r.setMsg("token失效，请重登录");
            return r;
        }
    }
}
